﻿using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class ScratchCard : System.Web.UI.Page
{
    private User oUser;
    protected void Page_Load(object sender, EventArgs e)
    {
        oUser = (User)Session["user"];
        if (!IsPostBack)
            if (oUser == null)
                Response.Redirect("/");
        LB_Msg.Text = "";
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        TB_Code.Text = TB_Code.Text.Trim();
        dulieuDataContext db = new dulieuDataContext();

        int count = (from o in db.cards where o.code == TB_Code.Text select o).Count();
        if (count != 0)
        {
            count = (from o in db.cards where o.code == TB_Code.Text && o.UserId==0 select o).Count();
            if (count != 0)
            {
                var obj = db.cards.SingleOrDefault(a => a.code == TB_Code.Text);
                if (obj != null)
                {
                    obj.UserId = oUser.ID;
                    db.SubmitChanges();
                    Response.Write(string.Format("<SCRIPT language='JavaScript'>alert('bạn đã nạp vào tài khoản {0:N0} VNĐ');</SCRIPT> ", obj.VND));
                    TB_Code.Text = "";

                    var NewUsers = db.Users.FirstOrDefault(o => o.UserName == oUser.UserName);
                    Session["user"] = NewUsers;
                }
            }
            else
            {
                LB_Msg.Text = "Thẻ đã được sử dụng.";
            }
        }
        else
        {
            LB_Msg.Text = "Thẻ không đúng.";
        }

    }
}